package com.example.smartclassroom.controller;

import com.example.smartclassroom.entity.CourseSelection;
import com.example.smartclassroom.entity.request.CourseRequest;
import com.example.smartclassroom.service.CourseSelectionService;
import com.example.smartclassroom.util.JsonDate;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

@RestController
@RequestMapping("/course")
public class CourseSelectionController {

    @Autowired
    private CourseSelectionService courseSelectionService;

    /**
     * 学生查看课程
     */
    @GetMapping("/queryAllCourseByStudent")
    public JsonDate queryAllCourse(CourseRequest courseRequest)
    {
        return courseSelectionService.queryAllCourseByStudent(courseRequest);
    }

    /**
     *查询学生已选课程信息、老师自己的课程信息
     */
    @GetMapping("/queryCourseByUserId")
    public JsonDate queryCourseByUserId(CourseRequest courseRequest)
    {

        return courseSelectionService.queryCourseByUserId(courseRequest);
    }
    /**
     * 添加学生选课信息
     */
    @PostMapping("/studentAddCourse")
    public JsonDate studentAddCourse(@RequestBody CourseSelection courseSelection)
    {
       return courseSelectionService.studentAddCourse(courseSelection);
    }

    /**
     * 删除学生选课信息
     */
    @PostMapping("/deleteCourseByStudentIdAndCourseId")
    public JsonDate deleteCourseByStudentIdAndCourseId(@RequestBody CourseSelection courseSelection)
    {
        return courseSelectionService.deleteCourseByStudentIdAndCourseId(courseSelection);
    }

    /**
     * 导出学生选课信息
     * @param response
     * @throws IOException
     */
    @RequestMapping("doOutExcelStudentCourse")
    public void doOutExcel(Integer studentId, HttpServletResponse response) throws IOException {

        List<CourseSelection> studentCourseList = courseSelectionService.queryCourseByUserIdOut(studentId);
        if (CollectionUtils.isEmpty(studentCourseList)) {
            throw new RuntimeException("没有数据");
        }

        // 1. 创建工作簿
        HSSFWorkbook workbook = new HSSFWorkbook();

        // 2. 在工作簿下创建工作表
        HSSFSheet sheet = workbook.createSheet("已选课程信息");

        // 3. 标题行
        HSSFRow titleRow = sheet.createRow(0);
        String[] titles = {"id","课程名称","类型","学分","可选人数","教室","课程开始","课程结束","星期","时段"};
        for (int i = 0; i < titles.length; i++) {
            HSSFCell cell = titleRow.createCell(i);
            cell.setCellValue(titles[i]);
        }

        // 4. 学生已选课程数据
        for (int i = 0; i < studentCourseList.size(); i++) {
            HSSFRow row = sheet.createRow(i + 1);
            CourseSelection info = studentCourseList.get(i);
            row.createCell(0).setCellValue(info.getId());
            row.createCell(1).setCellValue(info.getCourseName());
            row.createCell(2).setCellValue(info.getType());
            row.createCell(3).setCellValue(info.getScore());
            row.createCell(4).setCellValue(info.getNum());
            row.createCell(5).setCellValue(info.getRoomName());
            row.createCell(6).setCellValue(info.getStartTime());
            row.createCell(7).setCellValue(info.getEndTime());
            row.createCell(8).setCellValue(info.getWeekDay());
            row.createCell(9).setCellValue(info.getSegment());
        }

        // 自定义文件名，例如加上当前时间戳避免同名文件覆盖问题
        String currentTimeMillis = System.currentTimeMillis() + "";
        String fileName = "已选课程信息表_" + currentTimeMillis + ".xls";
        // 对文件名进行URL编码，防止中文乱码等问题
        String encodedFileName = URLEncoder.encode(fileName, "UTF-8").replace("+", "%20");

        // 设置响应头
        response.setContentType("application/vnd.ms-excel");
        // 动态文件名
        response.setHeader("Content-Disposition", "attachment;filename=" + encodedFileName);

        // 写入工作簿到响应流
        workbook.write(response.getOutputStream());
        workbook.close();
    }

}
